package org.scratchcrew.web.controller;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import org.scratchcrew.services.UserService;
import org.scratchcrew.web.jsf.FacesUtils;
import org.scratchcrew.web.vo.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

@Controller(value = "loginController")
@Scope(value = "request")
public class LoginController {
	private static final String FAIL_VIEW = "fail";

	private static final String BOARD_VIEW = "board";

	/**
	 * Key to the message indicating that user login failed.
	 */
	private static final String LOGIN_FAIL_MSG = "org.scratchcrew.web.controller.UserController.LOGIN_FAIL";

	private String userName;
	private String password;

	@Autowired
	private UserService userService;

	@Autowired
	private UserInfo user;

	@Autowired
	private MessageSource messageSource;

	/**
	 * Logins the user by setting the respective user name in session.
	 */
	public String login() {
		if (userService.findByNameAndPass(userName, password) != null) {
			user.setUserName(userName);

			return BOARD_VIEW;
		} else {
			FacesMessage error = new FacesMessage(messageSource.getMessage(
					LOGIN_FAIL_MSG, (Object[]) null, FacesUtils.getLocale()));

			FacesContext.getCurrentInstance().addMessage(null, error);

			return FAIL_VIEW;
		}
	}

	public void logout(ActionEvent e) {
		user.setUserName(null);
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
}
